package com.test.moudle.sys.oauth2;

import com.alibaba.fastjson.JSONObject;
import com.test.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class OAuth2Filter extends AuthenticatingFilter {

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {

        // 获取请求token
        String token = getRequestToken((HttpServletRequest) request);
        log.info("获取请求中的token|{}", token);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return new OAuth2Token(token);
    }

    /**
     * 判断是否登录
     * 在登录的情况下会走此方法，此方法返回true直接访问控制器
     * 如果isAccessAllowed方法返回True，则不会再调用onAccessDenied方法，如果isAccessAllowed方法返回False,则会继续调用onAccessDenied方法。
     * 而onAccessDenied方法里面则是具体执行登陆的地方。
     *
     * @param request     the incoming request
     * @param response    the outgoing response
     * @param mappedValue mappedValue
     * @return 判断是否登录
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        // OPTIONS请求直接通过，其他请求晓燕token
        boolean isAccessAllowed = ((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name());

        log.info("isAccessAllowed|{}", isAccessAllowed);

        return isAccessAllowed;
    }

    /**
     * 是否是拒绝登录
     *
     * @param request  the incoming request
     * @param response the outgoing response
     * @return 是否是拒绝登录
     * @throws Exception if there is a problem redirecting.
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        // 获取请求token，如果token不存在，直接返回401
        String token = getRequestToken((HttpServletRequest) request);
        log.info("获取请求中的token|{}", token);

        if (StringUtils.isBlank(token)) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Origin", "*");

            httpResponse.getWriter().print(R.error(HttpStatus.SC_UNAUTHORIZED, "invalid token"));

            return false;
        }
        return executeLogin(request, response);
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
                                     ServletResponse response) {

        log.debug("onLoginFailure");

        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        try {
            // 处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            JSONObject responseJson = new JSONObject();
            responseJson.put("code", 555);
            responseJson.put("msg", throwable.getMessage());
            httpResponse.getWriter().print(responseJson.toJSONString());
        } catch (IOException e1) {
            e.printStackTrace();
        }
        return false;
    }

    private String getRequestToken(HttpServletRequest httpRequest) {
        // 从header中获取token
        String token = httpRequest.getHeader("token");

        // 如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = httpRequest.getParameter("token");
        }

        log.debug("token|{}" + token);

        return token;
    }

}
